<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class WdminAjax extends Controller {

    public function __construct($ControllerName, $Action, $QueryString) {
        parent::__construct($ControllerName, $Action, $QueryString);
        $this->loadModel('Db');
    }

    /**
     * 上传群发封面图片
     * groupSendImageUpload
     */
    public function groupSendImageUpload($Query) {
        global $config;
        !isset($Query->name) && $Query->name = '';
        if (!empty($GLOBALS["HTTP_RAW_POST_DATA"])) {
            $targetPath = dirname(__FILE__) . "/../static/groupsend_upload/";
            $targetFileName = sha1(time()) . '-' . $Query->name;
            $targetFile = str_replace('//', '/', $targetPath) . $targetFileName;
            $state = file_put_contents($targetFile, $GLOBALS["HTTP_RAW_POST_DATA"]) > 0 ? 1 : 0;
        } else {
            $state = 0;
        }
        $this->echoJson(array(
            "status" => $state,
            "imagepath" => urlencode("http://" . $_SERVER['HTTP_HOST'] . $config->shoproot . 'static/groupsend_upload/' . $targetFileName),
            "imagename" => $targetFileName
        ));
    }

    /**
     * 创建群发页面
     * @param type $Query
     */
    public function alterGmessPage($Query) {
        global $config;

        // 是否为更新
        $isUpdate = isset($Query->isUpdate) ? $Query->isUpdate == 1 : false;

        if ($isUpdate) {
            /**
             * 修改保存gmess
             */
            $SQL = sprintf("UPDATE `gmess_page` SET `title` = '%s',`content` = '%s',`desc` = '%s',`catimg` = '%s' WHERE `id` = %s AND `appid` = '%s';", $_POST['title'], $_POST['content'], $_POST['desc'], urldecode($_POST['catimg']), (int) $_POST['msgid'], APPID);
            $rst = $this->Db->query($SQL);
            $this->echoJson(array(
                'status' => $rst ? 1 : 0
            ));
        } else {
            /**
             * 创建gmess
             */
            $SQL = sprintf("INSERT INTO `gmess_page` (`title`,`content`,`desc`,`catimg`,`createtime`,`appid`)"
                    . " VALUES ('%s','%s','%s','%s',NOW(),'%s');", $this->post('title'), $_POST['content'], $_POST['desc'], urldecode($_POST['catimg']), APPID);
            $rst = $this->Db->query($SQL);
            $ret = array();
            if ($rst) {
                $ret['status'] = 1;
                $ret['url'] = "http://" . $this->server('HTTP_HOST') . "$config->shoproot?/Gmess/view/id=" . $rst;
                $ret['msgid'] = $rst;
            } else {
                $ret['status'] = 0;
            }
            $this->echoJson($ret);
        }
    }

    // 获取订阅者列表
    // todo
    public function ajaxGetSubScribelist() {
        $this->loadModel('WechatSdk');
        $access_token = WechatSdk::getServiceAccessToken();
        $list = WechatSdk::getWechatSubscriberList($access_token);
        $list['accesstoken'] = $access_token;
        $this->echoJson($list);
    }

    // 上传群发统计数据
    public function UploadGroupSendStatData() {
        $SQL = sprintf("INSERT INTO `gmess_send_stat` (msg_id,send_date,send_count,receive_count,appid,msg_type) "
                . " VALUES (%s,NOW(),%s,%s,'%s','images');", $_POST['msgid'], $_POST['total'], $_POST['success'], APPID);
        $rst = $this->Db->query($SQL);
        echo $rst ? 1 : 0;
    }

    /**
     * 获取已发列表
     * @param type $Query
     */
    public function ajaxGetGroupSent($Query) {
        global $config;
        $list = $this->Db->query(sprintf("SELECT * FROM `gmess_page` RIGHT JOIN `gmess_send_stat` on gmess_page.id = gmess_send_stat.msg_id WHERE `gmess_page`.`appid` = '%s' ORDER BY `createtime` DESC;", APPID));
        foreach ($list as &$l) {
            $l['reach_rate'] = $l['receive_count'] == 0 ? 0 : sprintf('%.2f', ($l['receive_count'] / $l['send_count']) * 100);
            $l['createtime'] = date("n月d日", strtotime($l['createtime']));
            $l['href'] = "http://" . $this->server('HTTP_HOST') . "$config->shoproot?/Gmess/view/id=" . $l['msg_id'];
        }
        $this->Smarty->assign('list', $list);
        $this->show();
    }

    /**
     * 获取图文列表
     * @param type $Query
     */
    public function ajaxGetGmessList($Query) {
        global $config;
        $list = $this->Db->query(sprintf("SELECT * FROM `gmess_page` WHERE `gmess_page`.`appid` = '%s' ORDER BY `createtime` DESC;", APPID));
        foreach ($list as &$l) {
            $l['href'] = "http://" . $this->server('HTTP_HOST') . "$config->shoproot?/Gmess/view/id=" . $l['id'];
        }
        $this->Smarty->assign('list', $list);
        $this->show();
    }

    /**
     * 获取商品详细信息
     * @param type $Query
     */
    public function ajaxGetProductInfo($Query) {
        $id = intval($Query->id);
        $res = $this->Db->query("SELECT * FROM `products_info` pi LEFT JOIN product_onsale po ON po.product_id = pi.product_id WHERE pi.`product_id` = $id;");
        $this->echoJson($res[0]);
    }

}
